using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using MSRI.SmsService;
using MSRI.SmsSessions;
using MSRI.HelperClasses;
using System.DirectoryServices;
namespace AD_SMS_Service_Sample
{
    public partial class Form1 : Form
    {
        public SmsServiceClass SmsService = null;
        public SmsSessions MySessionList;
        public Form1()
        {
            InitializeComponent();
            try
            {
                SmsService = new SmsServiceClass("AD_SMS_Service_Sample");
                SmsService.OnDeliveryReportReceived += new OnDeliveryReportDelegate(SmsService_OnDeliveryReportReceived);
                SmsService.OnSmsReceived += new OnSmsReceivedDelegate(SmsService_OnSmsReceived);
                MySessionList = new SmsSessions();
                // Use SmsService.SendSms(SmsClass Sms) to send a Sms
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                Application.Exit();
            }
        }

        //
        // Your Code for Processing a received Sms goes here
        //
        SmsResponseClass SmsService_OnSmsReceived(SmsClass SmsMessage)
        {
            // Compose a Response Message
            SmsResponseClass response = new SmsResponseClass();
            SmsSession MySession = MySessionList[SmsMessage.Number];
            if (MySession == null)
            {
                MySession = new SmsSession();
                MySession.TimeInterval = 30 * 60; // 30 min
                MySession.SessionName = SmsMessage.Number;
                MySession.SessionContacts.Add(new SmsSessionContact(SmsMessage.Number));
                SmsMenu MySessionMenu = MakeMenu(SmsMessage.Body);
                MySession.SessionUserData = MySessionMenu;
                MySession.AttachSessionDelegate(MySessionMenu.ProcessMessage);
                MySessionList.Add(MySession);
            }
            response = MySession.CallSessionDelegate(SmsMessage);
            if (response.SessionState == ResponseSessionStateEnum.Delete)
                MySessionList.Remove(MySession);
            return response;

        }

        //
        // Your Code for Processing a deliveryreport goes here
        //
        void SmsService_OnDeliveryReportReceived(DeliveryReportClass DeliveryReport)
        {
            if (DeliveryReport.Status == DeliveryStatusEnum.Sent)
            {
                // Message Sent
            }
            else
            {
                // Message Sent Failed, You may want to retry
            }
        }


        public SmsMenu MakeMenu(string Alias)
        {
            DirectorySearcher objsearch = new DirectorySearcher();
            DirectoryEntry objdirentry = new DirectoryEntry("GC://corp.microsoft.com");
            objsearch.SearchRoot = objdirentry;
            objsearch.Filter = string.Format("(&(mail={0}*@*microsoft.com)((objectClass=person)))",Alias);
            objsearch.SearchScope = System.DirectoryServices.SearchScope.Subtree;
            objsearch.PropertiesToLoad.Add("displayname");
            objsearch.PropertiesToLoad.Add("mailnickname");
            objsearch.PropertiesToLoad.Add("mobile");
            objsearch.PropertiesToLoad.Add("title");
            objsearch.PropertiesToLoad.Add("physicalDeliveryOfficeName");
            //objsearch.PropertyNamesOnly = true;
            objsearch.PageSize = 100;
            objsearch.CacheResults = true;
            objsearch.Asynchronous = true;
            //SearchResult objresult = objsearch.FindOne();
            SearchResultCollection colresults = objsearch.FindAll();
            //int counter = 0;
            SmsMenu AliasMenu = new SmsMenu();
            AliasMenu.MoreKey = "0";
            AliasMenu.KeyTextSeparator = " ";
            SmsMenuItem AliasMenuItem = null;
            AliasMenu.Header = "Reply with number to get full details";
            if (colresults.Count == 0)
            {
                AliasMenuItem = new SmsMenuItem();
                AliasMenuItem.ResponseString = "No user found";
                AliasMenuItem.ResponseSessionState = ResponseSessionStateEnum.Delete;
                AliasMenuItem.Key = Alias;
                AliasMenu.StateList.Add(Alias);
                AliasMenu.AddSubMenuItem(AliasMenuItem);
            }
            else if (colresults.Count == 1)
            {
                SearchResult objresult = colresults[0];
                AliasMenuItem = new SmsMenuItem();
                AliasMenuItem.ResponseSessionState = ResponseSessionStateEnum.Delete;
                AliasMenuItem.Key = Alias;
                AliasMenu.StateList.Add(Alias);
                AliasMenuItem.ResponseString = "";
                if (objresult.Properties["displayname"].Count > 0)
                    AliasMenuItem.ResponseString += "Name:" + objresult.Properties["displayname"][0].ToString() + Environment.NewLine;
                if (objresult.Properties["mailnickname"].Count > 0)
                    AliasMenuItem.ResponseString += "Alias:" + objresult.Properties["mailnickname"][0].ToString() + Environment.NewLine;
                if (objresult.Properties["mobile"].Count > 0)
                    AliasMenuItem.ResponseString += "Mobile:" + cleanmobile(objresult.Properties["mobile"][0].ToString()) + Environment.NewLine;
                if (objresult.Properties["title"].Count > 0)
                    AliasMenuItem.ResponseString += "Title:" + objresult.Properties["title"][0].ToString() + Environment.NewLine;
                if (objresult.Properties["physicalDeliveryOfficeName"].Count > 0)
                    AliasMenuItem.ResponseString += "Address:" + objresult.Properties["physicalDeliveryOfficeName"][0].ToString() + Environment.NewLine;
                AliasMenu.AddSubMenuItem(AliasMenuItem);
            }
            else
            {
                int i=0;
                foreach (SearchResult objresult in colresults)
                {
                    try
                    {
                        i++;
                        AliasMenuItem = new SmsMenuItem();
                        AliasMenuItem.Key = i.ToString();
                        AliasMenuItem.ResponseString = "";
                        if (objresult.Properties["displayname"].Count > 0)
                            AliasMenuItem.ResponseString += "Name:" + objresult.Properties["displayname"][0].ToString() + Environment.NewLine;
                        if (objresult.Properties["mailnickname"].Count > 0)
                            AliasMenuItem.ResponseString += "Alias:" + objresult.Properties["mailnickname"][0].ToString() + Environment.NewLine;
                        if (objresult.Properties["mobile"].Count > 0)
                            AliasMenuItem.ResponseString += "Mobile:" + cleanmobile(objresult.Properties["mobile"][0].ToString()) + Environment.NewLine;
                        if (objresult.Properties["title"].Count > 0)
                            AliasMenuItem.ResponseString += "Title:" + objresult.Properties["title"][0].ToString() + Environment.NewLine;
                        if (objresult.Properties["physicalDeliveryOfficeName"].Count > 0)
                            AliasMenuItem.ResponseString += "Address:" + objresult.Properties["physicalDeliveryOfficeName"][0].ToString() + Environment.NewLine;
                        AliasMenu.AddSubMenuItem(AliasMenuItem);
                        AliasMenuItem.Text = objresult.Properties["displayname"][0].ToString();
                        AliasMenuItem.ResponseSessionState = ResponseSessionStateEnum.Delete;
                        AliasMenu.AddSubMenuItem(AliasMenuItem);
                    }
                    catch
                    {
                    }
                }
            }
            objsearch.Dispose();
            return AliasMenu;

        }

        private string cleanmobile(string number)
        {
            string temp;
            temp = "";
            foreach (char tempchar in number)
            {
                if ((tempchar >= '0' && tempchar <= '9') || tempchar == Convert.ToChar("+"))
                {
                    temp = temp + tempchar;
                }
            }
            if (temp.Length == 0)
                return temp;
            if (temp.Length == 10 && temp[0] == '9')
                temp = "+91" + temp;
            else if (temp.Length == 10 && (temp[0] == '4' || temp[0] == '2' || temp[0] == '8' || temp[0] == '5' || temp[0] == '7'))
                temp = "+1" + temp;
            else if (temp.Length == 11 && temp[0] == '1')
                temp = "+" + temp;
            else if (temp.Length == 12 && temp[0] == '9' && temp[1] == '1')
                temp = "+" + temp;
            return temp;

        }

    }
}